package com.xinghanlaser.applet.utils;

import com.tencentcloudapi.common.Credential;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;
import com.tencentcloudapi.common.profile.ClientProfile;
import com.tencentcloudapi.common.profile.HttpProfile;
import com.tencentcloudapi.sms.v20190711.SmsClient;
import com.tencentcloudapi.sms.v20190711.models.SendSmsRequest;
import com.tencentcloudapi.sms.v20190711.models.SendSmsResponse;
import com.xinghanlaser.applet.base.common.exception.ServiceException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

/**
 * <p>
 *
 * <p>
 *
 * @author: mftuo 陀铭峰
 * @since: 2024/5/7 13:44
 */
@Component
public class SMSUtil {
    @Value("${sms.signName}")
    private String signName = null;

    @Value("${sms.secretId}")
    private String secretId = null;

    @Value("${sms.secretKey}")
    private String secretKey = null;

    @Value("${sms.sdkAppId}")
    private String sdkAppId = null;

    @Value("${sms.templateId}")
    private String templateId = null;

    public void send(String phone, String msg){
        try {
            // 实例化一个认证对象
            Credential cred = new Credential(secretId, secretKey);

            // 实例化一个http选项，可选的，没有特殊需求可以跳过
            HttpProfile httpProfile = new HttpProfile();
            httpProfile.setEndpoint("sms.tencentcloudapi.com");

            // 实例化一个client选项，可选的，没有特殊需求可以跳过
            ClientProfile clientProfile = new ClientProfile();
            clientProfile.setHttpProfile(httpProfile);

            // 实例化要请求产品的client对象,clientProfile是可选的
            SmsClient client = new SmsClient(cred, "ap-guangzhou", clientProfile);

            // 实例化一个请求对象,每个接口都会对应一个request对象
            SendSmsRequest req = new SendSmsRequest();
            String[] phoneNumberSet = {"+86" + phone};

            req.setPhoneNumberSet(phoneNumberSet);

            req.setTemplateID(templateId);
            req.setSmsSdkAppid(sdkAppId);

            req.setSign(signName);

            String[] templateParamSet = {msg};
            req.setTemplateParamSet(templateParamSet);

            // 返回的resp是一个SendSmsResponse的实例，与请求对象对应
            SendSmsResponse resp = client.SendSms(req);

            // 输出json格式的字符串回包
            System.out.println(SendSmsResponse.toJsonString(resp));

        } catch (TencentCloudSDKException e) {
            throw new ServiceException("服务器发送验证码失败！");
        }
    }
}
